//
//  KABillDetailPager.swift
//  kano
//
//  Created by Frank on 2024/9/18.
//

import Foundation
import JXSegmentedView

class KABillDetailPager: KABaseVC {
    
    static let var_itemCellId = "KABillDetailPeriodCell"
    lazy var var_tableView: UITableView = {
        let var_tableView = UITableView(frame: CGRect(x: 0.0, y: 0, width: view.width-kscale(24), height: UIDevice.ka_viewHeight-kscale(234)), style: .grouped)
        var_tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        var_tableView.register(KABillDetailSectionHeader.self, forHeaderFooterViewReuseIdentifier: "KABillDetailSectionHeader")
        var_tableView.dataSource = self
        var_tableView.delegate = self
        var_tableView.separatorStyle = .none
        var_tableView.separatorColor = UIColor.clear
        var_tableView.bounces = false
        return var_tableView
    }()
    
    var model: KABillDetailModel
    //是否是分期已还款页
    var isRepaidPage: Bool
    lazy var var_dataArray = [KASectionInfo]()
    //分期数据
    var subLoanData: [KABillDetailSubLoans] = []
    
    var loanGid: String = ""
    
    init(with model: KABillDetailModel, isRepaidPage: Bool, loanGid: String) {
        self.model = model
        self.loanGid = loanGid
        self.isRepaidPage = isRepaidPage
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        view.addSubview(var_tableView)
        configData()
    }
    
    func configData() {
        let amount = KARowInfo(title: "Loan amount", isFirst: true, type: .loanAmount)
        let interest = KARowInfo(title: "Interest", type: .interest)
        let fee = KARowInfo(title: "Fee", type: .fee, showTitleTip: true)
        //待还总金额
        let amountDue = KARowInfo(title: "Amount due", type: .amountDue, showPartingLine: true)
        //逾期费
        let penaltyFee = KARowInfo(title: "Penalty fee", type: .penaltyFee)
        //逾期天数
        let overDays = KARowInfo(title: "Days overdue", type: .overDays)
        
        let charge = KARowInfo(title: "Handling charge", type: .loanCharge, showTitleTip: true)
        let loanTime = KARowInfo(title: "Loan time", type: .loanTime, showPartingLine: true)
        let dueDate = KARowInfo(title: "Due date", type: .dueDate)
        let cycle = KARowInfo(title: "Borrowing cycle", type: .borrowingCycle)
        let number = KARowInfo(title: "Loan number", isLast: true, type: .loanNumber, showPartingLine: true)
        
        var loanInfoSec: KASectionInfo = KASectionInfo()
        //蝌蚪贷
        if model.tadpoleLoanIndicator {
            let sectionList = model.ka_hasOverDueBill() ? [amount,interest,fee,amountDue,penaltyFee, overDays,loanTime,dueDate,cycle,number] : [amount,interest,fee,loanTime,dueDate,cycle,number]
            
            loanInfoSec = KASectionInfo(showHeader: true, open: true, sectionTitle: "Loan details", sectionSubTitle: "", sectionList: sectionList, type: .loanInfo)
        }
        //大额
        else if model.secondaryLoanTotal > 0 {
            let sectionList = model.ka_hasOverDueBill() ? [amount,fee,amountDue,penaltyFee, overDays,loanTime,dueDate,cycle,number] : [amount,fee,loanTime,dueDate,cycle,number]
            loanInfoSec = KASectionInfo(showHeader: true, open: true, sectionTitle: "Loan details", sectionSubTitle: "", sectionList: sectionList, type: .loanInfo)
        }
        //小额
        else {
            let sectionList = model.ka_hasOverDueBill() ? [amount,interest,fee,amountDue,penaltyFee, overDays,loanTime,dueDate,cycle,number] : [amount,interest,fee,loanTime,dueDate,cycle,number]
            loanInfoSec = KASectionInfo(showHeader: true, open: true, sectionTitle: "Loan details", sectionSubTitle: "", sectionList: sectionList, type: .loanInfo)
        }
        
        let loanPrivacySec = KASectionInfo(showHeader: true, open: true, sectionTitle: "Loan agreement", sectionSubTitle: "", sectionList: [], type: .loanPrivacy)
        
        var_dataArray.append(loanInfoSec)
        var_dataArray.append(loanPrivacySec)
        
        //还款记录
        if model.businessProcessType > 0 {
            let repaymentRecordSec = KASectionInfo(showHeader: true, open: true, sectionTitle: "Repayment record", sectionSubTitle: "", sectionList: [], type: .repaymentRecord)
            var_dataArray.append(repaymentRecordSec)
        }
        
        
        //MARK: - Attention
        //大额 或 蝌蚪贷
        if model.secondaryLoanTotal > 0 {
            let unRepayment =  model.transactionUserType?.filter {$0.emailProvider != 3}
            let repayment = model.transactionUserType?.filter {$0.emailProvider == 3}
            self.subLoanData = (isRepaidPage ? repayment : unRepayment) ?? []
        }
        //小额
        else {
            self.subLoanData = []
        }
        
        //已还款分页
        if isRepaidPage {
            let totalValue = subLoanData.map { $0.businessProcessType }.reduce(0, +)
            let subLoanSec = KASectionInfo(showHeader: true, open: true, sectionTitle: "\(subLoanData.count) period paid", sectionSubTitle: "₦\(totalValue)", sectionList: [], type: .subLoan)
            var_dataArray.insert(subLoanSec, at: 0)
        }
        
        else if subLoanData.count > 0 {
            let totalValue = subLoanData.map { $0.remainingFunds }.reduce(0, +)
            let subLoanSec = KASectionInfo(showHeader: true, open: true, sectionTitle: "Pending \(subLoanData.count) period", sectionSubTitle: "₦\(totalValue)", sectionList: [], type: .subLoan)
            var_dataArray.insert(subLoanSec, at: 0)
        } else {
        }
    }
}

extension KABillDetailPager : UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return var_dataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionModel = var_dataArray[section]
        switch sectionModel.type {
        case .subLoan:
            return sectionModel.open ? subLoanData.count : 0
        case .loanInfo:
            return sectionModel.open ? sectionModel.sectionList.count : 0
        case .loanPrivacy:
            return 0
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let sectionModel = var_dataArray[indexPath.section]
        switch sectionModel.type {
        case .subLoan:
            let model = subLoanData[indexPath.row]
            let var_cell: KABillDetailPeriodCell = KABillDetailPeriodCell.ka_cell(for: tableView)
            var_cell.titleLabel.text = "\(model.primaryIndex) phase"
            var_cell.amountLabel.text = model.remainingFunds == 0 ? "₦\(model.businessProcessType.separatorString())" : "₦\(model.remainingFunds.separatorString())"
            var_cell.dateLabel.text = Date.ka_stringWith(timestamp: model.dueDateTime, format: "dd/MM/yyyy")
            if indexPath.row == 0 {
                var_cell.topCorner = true
            } else if (indexPath.row == subLoanData.count - 1) {
                var_cell.bottomCorner = true
            } else if (indexPath.row == subLoanData.count - 1 && indexPath.row == 0) {
                var_cell.topCorner = true
                var_cell.bottomCorner = true
            }
            return var_cell
        case .loanInfo:
            let cellModel = sectionModel.sectionList[indexPath.row]
            let var_cell: KABillDetailCell = KABillDetailCell.ka_cell(for: tableView)
            var_cell.titleLabel.text = cellModel.title
            var_cell.var_explainBtn.isHidden = cellModel.showTitleTip ? false : true
            var_cell.dashedLine.isHidden = cellModel.showPartingLine ? false : true
            var_cell.explainHandler = {
                let subStr = "Fees include payment channel fees, repayment channel fees, credit system service fees, loan platform management fees, risk consulting services, etc. "
                let alert = KAAlertView.alert(withTitle: "Handling fee details", subtitle: subStr) { clickedTitle in
                }
                alert.addAction(KAAlertAction(title: "Confirm", titleColor: .blue, backgroundColor: .clear))
                alert.show()
            }
            
            var fee = 0.00
            var interst = 0.00
            
            //蝌蚪贷、小额, 需要分别展示手续费fee和利息interest；
            if model.tadpoleLoanIndicator {
                interst = model.overdueStatus * 8 / 10000 * Double(model.firstPeriod)
                fee = model.chargeFee - interst
            }
            //大额直接展示手续费fee，不拆分
            else if model.secondaryLoanTotal > 0 {
                fee = model.chargeFee
            }
            else {
                interst = model.overdueStatus * 8 / 10000 * Double(model.loanDuration)
                fee = model.chargeFee - interst
            }
            
            var_cell.subLabel.textColor = .black
            switch cellModel.type {
            case .loanAmount:
                var_cell.subLabel.text = "\(model.overdueStatus.separatorString())"
            case .interest:
                var_cell.subLabel.text = "\(interst.separatorString())"
            case .fee:
                var_cell.subLabel.text = "\(fee.separatorString())"
            case .amountDue:
                var_cell.subLabel.text = "\(model.registrationConfirmation.separatorString())"
            case .penaltyFee:
                var_cell.subLabel.text = "\(model.validationCode.separatorString())"
                var_cell.subLabel.textColor = .colorFF3644
            case .overDays:
                var_cell.subLabel.text = "\(model.ka_overDays()) day"
            case .loanCharge:
                var_cell.subLabel.text = "\(model.registrationConfirmation)"
            case .loanTime:
                var_cell.subLabel.text = Date.ka_stringWith(timestamp: model.loanTimeline, format: "dd/MM/yyyy")
            case .dueDate:
                var_cell.subLabel.text = Date.ka_stringWith(timestamp: model.dueDateTime, format: "dd/MM/yyyy")
            case .borrowingCycle:
                var_cell.subLabel.text = "\(model.loanDuration) days"
            case .loanNumber:
                var_cell.subLabel.text = "\(model.orderSequenceNumber)"
            default: break
            }
            var_cell.cellModel = cellModel
            return var_cell
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let sectionModel = var_dataArray[indexPath.section]
        switch sectionModel.type {
        case .subLoan:
            //            if indexPath.row == 0 || indexPath.row == subLoanData!.count - 1 {
            //                return kscale(35)
            //            } else {
            //                return kscale(15)
            //            }
            return kscale(35)
        case .loanInfo:
            return kscale(33)
        case .loanPrivacy:
            return .leastNonzeroMagnitude
        default:
            return .leastNonzeroMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionModel = var_dataArray[section]
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "KABillDetailSectionHeader") as! KABillDetailSectionHeader
        header.var_handler = { [self] in
            if sectionModel.type == .loanPrivacy {
                loanAgreement()
            } else if sectionModel.type == .repaymentRecord {
                ka_requestRepaymentRecord()
            } else {
                sectionModel.open = !sectionModel.open
                tableView.reloadData()
            }
        }
        header.titleLabel.text = sectionModel.sectionTitle
        header.detailTitle.text = sectionModel.sectionSubTitle
        header.open = sectionModel.open
        if section == var_dataArray.count - 1 {
            header.topCorner = false
            header.bottomCorner = true
        }
        return header
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return kscale(44)
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func loanAgreement() {
        view.showLoading()
        let paraDic: [String : Any] = [
            "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions,
            "loanTransactionIdentifier" : loanGid
        ]
        billProvider.request(.loanAgreement(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAAgreemetModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            model.productIdentifier = content.productIdentifier
                            model.optOutURL = content.optOutURL
                            model.dueDateArr = model.ka_getDueDate()
                            navigationController?.pushViewController(KALoanAgreement(with: model), animated: true)
                            
                            let btnInfo = KABtnInfo(eleId: "ContractFromBill_Nav", pageId: "BillDetail_Access", clickTime: Date.ka_currentData())
                            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    func ka_requestRepaymentRecord() {
        let paraDic: [String : Any] = [
            "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions,
            "loanTransactionIdentifier" : loanGid,
            "pageIndex": 0,
            "pageSize": 0
        ]
        view.showLoading()
        billProvider.request(.repaymentRecord(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KARepaymentListModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            let pusher = KARepaymentRecordPusher(data: content.repaymentEntries ?? [])
                            pusher.ka_show()
                            
                            let btnInfo = KABtnInfo(eleId: "BillToLoanList_Nav", pageId: "BillStatement_Overview", clickTime: Date.ka_currentData())
                            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
                        }
                    }
                    
                    
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}



extension KABillDetailPager: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        view.backgroundColor = .orange
        return view
    }
}
